<template>
<div>
    <van-nav-bar title="黑马头条-登录" />
    <van-form @submit="onSubmit">
  <van-field
    v-model="formLogin.mobile"
    type='tel'
    name="手机号"
    label="手机号"
    placeholder="请输入手机号"
    required
    :rules="[{ required: true, message: '你没写手机号啊喂', pattern:/^1[3-9]\d{9}$/, trigger:'onChange'}]"
  />
  <van-field
    v-model="formLogin.code"
    type="password"
    name="密码"
    label="密码"
    placeholder="请输入密码"
    required
    :rules="[{ required: true, message: '密码没写呢', pattern:/^\d{6}$/, trigger:'onChange' }]"
  />
  <div style="margin: 16px;">
    <van-button round block type="info" native-type="submit" :loading="isLoading" :disabled="isLoading" loading-text="拼命加载中">提交</van-button>
  </div>
</van-form>
</div>
</template>

<script>
// import { loginAPI } from '@/api'
import { mapActions } from 'vuex'
import { Notify } from 'vant'
export default {
  name: 'Login',
  data () {
    return {
      formLogin: {
        mobile: '13888888888',
        code: '246810' // 默认只能用246810后台规定了
      },
      isLoading: false
    }
  },
  methods: {
    ...mapActions(['asyncLoginAction']),
    async onSubmit (values) {
      // 开始请求时变为true，加载中
      this.isLoading = true
      try {
        // const res = await loginAPI(this.formLogin)
        // const { refresh_token, token } = res.data.data
        // console.log(token)
        // console.log(refresh_token)
        // 请求结束变为false，加载结束
        this.isLoading = false
        await this.asyncLoginAction(this.formLogin)
        Notify({ type: 'success', message: '登陆成功' })
        this.$router.replace({
          path: '/layout'
        })
      } catch (err) {
        console.err(err)
        // 发生错误时也结束加载
        this.isLoading = false
        Notify({ type: 'warning', message: '手机号或密码错误' })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.van-nav-bar {
  background-color: #007bff;
}
/deep/.van-nav-bar__title {
  color: #fff;
}
</style>
